<?php
namespace app\model;

use app\model\BaseModel;
use app\model\SourceType;

class Source extends BaseModel{
    // 构建模型关联关系
    public function sourceType(){
        return $this->hasOne(SourceType::class,'type');
    }
    // 保存一个资源 通过扩展自动检测类型
    public function insertSource($name='上传的文件',$extend,$user_id,$href){
        $type = $this->judgeType($extend);
        if(!$type){
            return false;
        }
        return $this->save([
            'name'    => $name,
            'type'    => $type,
            'user_id' => $user_id,
            'href'    => $href,
            'state'   => 1
        ]);
    }
    // 判断当前Type是表中的那个类型
    private function judgeType($extend){
        $type = '';
        switch(strtolower($extend)){
            case 'jpg':
            case 'jpeg':
            case 'png':
            case 'bmp':
                $type = 'IMAGE';
                break;
            case 'pdf':
                $type = 'PDF';
                break;
            case 'mp4':
            case 'ogg':
            case 'mpeg':
            case 'avi':
            case '3gp':
                $type = 'VIDEO';
                break;
            case 'mp3':
            case 'wav':
            case 'wma':
            case 'flc':
                $type = 'AUDIO';
                break;
            default:
                $type = 'OTHER';
                break;
        }
        $typeArr = SourceType::where(['code'=>$type])->findOrEmpty();
        return array_key_exists('id',$typeArr) ? $typeArr['id']: false;
    }
}